<template>
  <!-- <selectFarmType> -->
  <div class="binding">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span></span>
        <!-- <el-button
            style="float: right"
            icon="el-icon-circle-check"
          >完成</el-button> -->
        <el-button
          style="float: right; margin-right: 10px"
          icon="el-icon-edit-outline"
          @click="edit"
        >修改</el-button>
        <el-button
          style="float: right; margin-right: 10px"
          icon="el-icon-edit-outline"
          @click="add"
        >添加</el-button>
      <!-- <el-button style="float: right" icon="el-icon-plus">添加</el-button> -->
      </div>
      <div class="card-main">
        <div class="card-main-left">
          <el-tree
            ref="cascaderone"
            :data="tableDatas"
            draggable
            node-key="functionNo"
            :props="treePropstypes"
            @node-click="treeclick($event, 'edit')"
            @check-change="handleCheckChange"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span>
                <!-- <el-button
                  v-if="node.level !== 3"
                  type="text"
                  size="mini"
                  class="text-btn-cursor"
                  style="margin-left: 20px;color:#61aa47"
                  @click="() => editlineallmes(node, data)"
                >
                  修改名称
                </el-button> -->
                <el-button
                  type="text"
                  size="mini"
                  class="text-btn-cursor cursor-delete"
                  style="margin-left: 80px"
                  @click="() => dellineallmes(node, data)"
                >
                  删除
                </el-button>
              </span>
            </span></el-tree>
        </div>
        <div class="card-main-right">
          <div class="select-farmtype" style="display: none">
            <div
              v-for="(item, index) in basefarmtype"
              :key="index"
              class="farmtypebutton"
              :class="
                item.virtualSystemNo === nowselectmessage.virtualSystemNo
                  ? 'farmtypebutton-active'
                  : ''
              "
              @click="slecttype(item)"
            >
              <div class="but-line">
                {{ item.virtualSystemName }}
              </div>
            </div>
          </div>
          <el-tree
            ref="cascader"
            :data="tableData"
            node-key="functionNo"
            :props="treePropstype"
            @node-click="treeclick($event, 'add')"
            @check-change="handleCheckChange"
          > <span slot-scope="{ node, data }" class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span style="margin-left: 80px;">
              <!-- <el-button
                  v-if="node.level !== 3"
                  type="text"
                  size="mini"
                  class="text-btn-cursor"
                  style="margin-left: 20px;color:#61aa47"
                  @click="() => editlineallmes(node, data)"
                >
                  修改名称
                </el-button> -->
              描述： {{ data.remarks }}
            </span>
          </span></el-tree>
        </div>
      </div>
    </el-card>
    <el-dialog
      title="字段名称"
      :visible.sync="dialogExaminesVisible"
      width="30%"
      class="Exam"
      :modal="false"
    >
      <el-form
        ref="ExamineForms"
        label-position="left"
        :model="ExamineForms"
        class="el-form"
      >
        <el-form-item
          :rules="[{
            message: '字段名称不能为空',
            trigger: 'blur',
            required: true
          }]"
          label="字段名称:"
          prop="fieldName"
          class="w100p"
        >
          <el-input v-model="ExamineForms.fieldName" clearable />
        </el-form-item>
        <el-form-item
          label="描述:"
          prop="remarks"
          class="w100p"
        >
          <el-input v-model="ExamineForms.remarks" clearable />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button class="zh-button-one" @click="dialogExaminesVisible = false">取 消</el-button>
        <el-button class="zh-button-two" type="primary" @click="savees(saveStauts)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
  <!-- </selectFarmType> -->
</template>

<script>
import axios from "axios";
import { mymixin } from "@/utils/mixins";
// import selectFarmType from "./selectFarmTypev3/index.vue";
export default {
  components: {

  },
  mixins: [mymixin],
  props: {
    patternNo: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      treePropstype: {
        children: "child",
        label: "fieldName"
        // 'show-checkbox': true,
        // 'check-strictly': true
      },
      treePropstypes: {
        children: "child",
        label: "fieldName"
        // 'show-checkbox': true,
        // 'check-strictly': true
      },
      tableDatas: [],
      databaseName: 'DB_TDW1_PUBLIC',
      farmtypemessage: '',
      nodesInfo: [],
      dialogExaminesVisible: false,
      ExamineForms: {},
      basefarmtype: {},
      nowselectmessage: { description: "大田种植", farmingTypeNo: 1 },
      saveStauts: ''
    };
  },
  watch: {
    patternNo: {
      handler(val) {
        // console.log(val)
        // const that = this
        // that.$refs['cascader'].setCheckedNodes([])
        this.gettabledataListLeft()
      }
    }
  },
  created() {
    // console.log(this.patternNo)
    // const that = this
    // that.$refs['cascader'].setCheckedNodes([])
    this.gettabledataListLeft()
    this.getallfarmlist()
  },
  mounted() {
    this.gettabledataList();
  },
  methods: {
    editlineallmes(e, x) {
      this.ExamineForms = {
        patternNo: this.patternNo,
        functionNo: x.functionNo,
        muneName: x.visibleName
      }
    },
    savees(e) {
      this.$refs['ExamineForms'].validate(async (valid) => {
        if (valid) {
          if (e === "add") {
            let params = {
              ...this.ExamineForms,
              fieldTemplateNo: this.patternNo
            };
            const { data: mes } = await axios({
              method: "post",
              url: this.$webSerUrlPro + "config/fieldTemplateConfig/add",
              headers: {
                databaseName: this.databaseName
              },
              data: params
            });
            // console.log(mes)
            if (mes.code === 1) {
              // this.tableData = mes.data || [];
              this.$message.success("修改成功");
              this.gettabledataListLeft()
              this.dialogExaminesVisible = false
              // this.resetWarn()
              // this.totalSize = mes.data.totalElements
              this.resetActionBar();
            } else {
              this.$message.warning("修改失败");
            }
          } else if (e === 'edit') {
            let params = {
              ...this.ExamineForms
            };
            const { data: mes } = await axios({
              method: "post",
              url: this.$webSerUrlPro + "config/fieldTemplateConfig/edit",
              headers: {
                databaseName: this.databaseName
              },
              data: params
            });
            // console.log(mes)
            if (mes.code === 1) {
              // this.tableData = mes.data || [];
              this.$message.success("修改成功");
              this.gettabledataListLeft()
              this.dialogExaminesVisible = false
              // this.resetWarn()
              // this.totalSize = mes.data.totalElements
              this.resetActionBar();
            } else {
              this.$message.warning("修改失败");
            }
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    dellineallmes(e, x) {
      this.$confirm('此操作永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let params = {
          fieldTemplateConfigId: x.fieldTemplateConfigId
        };
        const { data: mes } = await axios({
          method: "get",
          url: this.$webSerUrlPro + "config/fieldTemplateConfig/del",
          headers: {
            databaseName: this.databaseName
          },
          params: params
        });
          // console.log(mes)
        if (mes.code === 1) {
          // this.tableData = mes.data || [];
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.gettabledataListLeft()
          this.resetWarn()
          // this.totalSize = mes.data.totalElements
          this.resetActionBar();
        } else {
          this.$message.warning("删除失败");
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
      // v3/config/patternFunctionMapper/del
    },
    // ---
    // getfarmtypemessage(e) {
    //   const that = this
    //   this.farmtypemessage = e;
    //   // this.getbasemessage(e.farmingTypeNo)
    //   that.$refs['cascader'].setCheckedNodes([])
    //   this.gettabledataListLeft()
    // },
    // 点击某一节点
    async treeclick(e, x) {
      // let nodesInfo = this.$refs['cascader'].getCheckedNodes()
      // console.log(nodesInfo)
      // this.formData = {};
      this.saveStauts = x
      this.ExamineForms = JSON.parse(JSON.stringify(e));
      // console.log(e)

      this.editActive = true;
      this.addActive = true;
      this.saveActive = false;
      this.cancelActive = false;
      this.canInput = false;
      this.editActive = true;
    },
    handleCheckChange(e) {
      let nodesInfo = this.$refs['cascader'].getCheckedKeys()
      let nodesInfos = this.$refs['cascader'].getHalfCheckedKeys()
      this.nodesInfo = [...nodesInfo, ...nodesInfos]
    },
    // 获取表格信息
    async gettabledataListLeft(e) {
      let params = {
        // page: this.currentPage,
        // size: this.pageSize,
        // entity: {
        fieldTemplateNo: this.patternNo

        // }
      };
      const { data: mes } = await axios({
        method: "post",
        url: this.$webSerUrlPro + "config/fieldTemplateConfig/queryByCondition",
        headers: {
          databaseName: this.databaseName
        },
        data: params
      });
      // console.log(mes)
      if (mes.code === 1) {
        this.tableDatas = mes.data || [];
        // this.totalSize = mes.data.totalElements
        this.resetActionBar();
      } else {
        this.$message.warning("获取表格失败");
      }
    },
    slecttype(e) {
      this.nowselectmessage = e;
      this.resetWarns(e)
    },
    // 获取重复id
    async resetWarns(e) {
      const that = this
      const { data: mes } = await axios({
        method: "post",
        url: this.$webSerUrlPro + "config/vSFunctionMapper/queryByCondition",
        headers: {
          databaseName: this.databaseName
        },
        data: {
          virtualSystemId: e.virtualSystemId
        }
      });
      // console.log(mes)
      if (mes.code === 1) {
        let data = mes.data
        that.$refs['cascader'].setCheckedNodes([])
        data.forEach(item => {
          // nowcheck.push(item.functionPermissionId)
          that.$nextTick(
            () => {
            // console.log(item.functionPermissionId)
            // 设置目前所有节点
              // that.$refs.tree.setCheckedKeys([item.routeId], true)
            // 设置某个节点
              that.$refs['cascader'].setChecked(item.function.functionNo, true)
            }
          )
        });
      } else {
        this.$message.warning("获取表格失败");
      }
    },
    // 获取模板的·所有类型
    // 获取所有农业类型
    getallfarmlist() {
      axios({
        method: "post",
        url: this.$webSerUrlPro + "config/virtualSystem/queryByCondition",
        headers: {
          databaseName: this.databaseName
        },
        data: {},
        params: {}
      }).then(response => {
        let farmmes = response.data.data
        if (farmmes && farmmes[0]) {
          this.basefarmtype = farmmes
          // this.slecttype(farmmes[0])
        }
      })
    },
    // 获取重复id
    async resetWarn() {
      const that = this
      const { data: mes } = await axios({
        method: "post",
        url: this.$webSerUrlPro + "config/patternFunctionMapper/queryByCondition",
        headers: {
          databaseName: this.databaseName
        },
        data: {
          patternNo: this.patternNo
        }
      });
      // console.log(mes)
      if (mes.code === 1) {
        let data = mes.data
        data.forEach(item => {
          // nowcheck.push(item.functionPermissionId)
          that.$nextTick(
            () => {
            // console.log(item.functionPermissionId)
            // 设置目前所有节点
              // that.$refs.tree.setCheckedKeys([item.routeId], true)
            // 设置某个节点
              that.$refs['cascader'].setChecked(item.functionNo, true)
            }
          )
        });
      } else {
        this.$message.warning("获取表格失败");
      }
    },
    // 获取表格信息
    async gettabledataList() {
      let params = {
      };
      const { data: mes } = await axios({
        method: "post",
        url: this.$webSerUrlPro + "config/field/queryByCondition",
        headers: {
          databaseName: this.databaseName
        },
        data: params
      });
      // console.log(mes)
      if (mes.code === 1) {
        this.tableData = mes.data || [];
        // this.totalSize = mes.data.totalElements
        this.resetWarn()
        this.resetActionBar();
      } else {
        this.$message.warning("获取表格失败");
      }
    },
    async add() {
      this.dialogExaminesVisible = true
      this.saveStauts = 'add'
    },
    async edit() {
      this.dialogExaminesVisible = true
      this.saveStauts = 'edit'
    }
  }
};
</script>

<style lang="scss" scoped>
    @import "~@/styles/variables.scss";

.binding {
  height: 100%;
  width: 100%;
  ::v-deep {
    .el-card {
      height: 100%;
      background-color: #002834;
      color: #54dee2;
      border-color: #005e6a;
      .el-card__header {
        border-bottom-color: #0092a5;
        border-bottom-style: dashed;
        .el-button {
          border: 1px solid #54dee2;
          padding: 5px;
          background: initial;
          color: #54dee2;
        }
        .el-button:focus,
        .el-button:hover {
          color: #ecf5ff;
          border-color: #c6e2ff00;
          background-color: #54dee2;
        }
      }
      .el-card__body {
        height: 100%;
      }
      .card-main {
        height: 90%;

        display: flex;
        flex-direction: row;
        justify-content: space-around;
        align-items: center;
        flex-wrap: nowrap;
        & > div {
          flex: 1;
          overflow-y: auto;
          height: 100%;
        }
      }
    }
    .Exam {
      .el-dialog {
        width: 20%;
        height: 30vh;
        min-width: 30%;
        .el-dialog__body {
          height: 18vh;
        }
      }
    }
  }
  .select-farmtype {
  width: 100%;
  height: 50px;
  overflow-x: auto;
  display: flex;
  flex-direction: row;
  align-items: center;
  overflow-x: auto;
  // &:first-of-type {
    // margin-left: 15px;
  // }
  &:last-of-type {
    margin-right: 15px;
  }
  .farmtypebutton {
    width: 129px;
    height: 30px;
    background: #00525D;
    border-radius: 48px 48px 48px 48px;
    opacity: 1;
    overflow: hidden;
    // border: 1px solid #005b5f;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    margin-right: 12px;
    .but-line {
      width: 100%;
      height: 28px;
      text-align: center;
      font-size: 14px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: $textColor;
      line-height: 28px;
    }

  }
  .farmtypebutton-active {
      background: #009fa5;
  }
  .farmtypebutton:hover{
  background: #009fa5;
  }
}
}

</style>
